package com.mystnihon.freeremote.ui.fragment;

import java.util.ArrayList;
import java.util.Observable;

import org.json.mine.JSONObject;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import ca.benow.transmission.model.TorrentFile;
import ca.benow.transmission.model.TorrentPeer;
import ca.benow.transmission.model.TorrentStatus;
import ca.benow.transmission.model.TorrentStatus.TorrentField;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.mystnihon.freeremote.FreeRemoteApplication;
import com.mystnihon.freeremote.R;
import com.mystnihon.freeremote.manager.TransmissionManager;
import com.mystnihon.freeremote.manager.TransmissionManager.TransmissionResult;
import com.mystnihon.freeremote.manager.TransmissionManager.TransmissionResult.ActionType;
import com.mystnihon.freeremote.util.FTimer;
import com.mystnihon.freeremote.util.FTimer.FTimerListener;

public class TorrentDetailsFragment extends DefaultObserverSherlockFragment implements FTimerListener, TabListener, OnPageChangeListener {

	public static TorrentDetailsFragment newInstance() {
		return new TorrentDetailsFragment();
	}

	public static final String TORRENT_ID = "torrentId";
	public static final String TORRENT_JSON = "torrentJson";

	private static final TorrentStatus.TorrentField[] requestedFields = new TorrentField[] { TorrentField.id, TorrentField.name, TorrentField.status, TorrentField.percentDone, TorrentField.addedDate,
			TorrentField.startDate, TorrentField.doneDate, TorrentField.files, TorrentField.uploadRatio, TorrentField.peers, TorrentField.uploadedEver, TorrentField.downloadedEver,
			TorrentField.downloadDir, TorrentField.totalSize, TorrentField.sizeWhenDone, TorrentField.peersConnected, TorrentField.peerLimit };
	private static final int DEFAULT_REFRESH_TIME = 30;

	private ListView mListViewFiles;
	private ListView mListViewPeers;

	private TransmissionManager mManager;
	private TorrentStatus mTorrentStatus;
	private FTimer mTimer;

	private TorrentFileAdapter mFileAdapter;
	private PeerFileAdapter mPeerAdapter;
	private ViewPager mViewPager;
	private View mView;

	private ActionBar mActionBar;
	private ActionBar.Tab mTabFile;
	private Tab mTabPeers;
	private Tab mTabOptions;

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_torrent_details, null);
		mListViewFiles = (ListView) mView.findViewById(R.id.fr_torrent_details_file_list);
		mListViewFiles.setEmptyView(mView.findViewById(R.id.fr_torrent_details_file_list_empty));
		mListViewPeers = (ListView) mView.findViewById(R.id.fr_torrent_details_peer_list);
		mListViewPeers.setEmptyView(mView.findViewById(R.id.fr_torrent_details_peer_list_empty));
		
		WizardPagerAdapter mAdapter = new WizardPagerAdapter();
		mViewPager = (ViewPager) mView.findViewById(R.id.fr_torrent_details_right_panel);
		mViewPager.setAdapter(mAdapter);
		mViewPager.setOnPageChangeListener(this);

		mFileAdapter = new TorrentFileAdapter(getSherlockActivity());
		mPeerAdapter = new PeerFileAdapter(getSherlockActivity());
		mListViewFiles.setAdapter(mFileAdapter);
		mListViewPeers.setAdapter(mPeerAdapter);
		return mView;
	};

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initTimer(savedInstanceState);
		initTorrent();
		initTabs();
	}

	@Override
	public void onResume() {
		super.onResume();
		mTimer.cleanMessages();
		refreshListDataSet();
		mTimer.setRefreshTime(PreferenceManager.getDefaultSharedPreferences(getSherlockActivity()).getInt(getString(R.string.pref_key_seedbox_refresh_time), DEFAULT_REFRESH_TIME) * 1000L);
		mTimer.initialize();
	}

	@Override
	public void onPause() {
		mTimer.cleanMessages();
		super.onPause();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mTimer.onSaveInstanceState(outState);
	}

	public void setData(String json) {
		if (json != null && json.length() > 0) {
			mTorrentStatus = new TorrentStatus(new JSONObject(json));
		}
	}

	private void initTimer(Bundle savedInstanceState) {
		mTimer = new FTimer();
		mTimer.onRestoreInstanceState(savedInstanceState);
		mTimer.setFTimerListener(this);

	}

	private void initTabs() {
		mActionBar = getSherlockActivity().getSupportActionBar();
		mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		mTabFile = mActionBar.newTab();
		mTabFile.setText(R.string.seedbox_torrent_files);
		mTabFile.setTabListener(this);
		mTabPeers = mActionBar.newTab();
		mTabPeers.setText(R.string.seedbox_torrent_peer);
		mTabPeers.setTabListener(this);
		mTabOptions = mActionBar.newTab();
		mTabOptions.setText(R.string.seedbox_torrent_options);
		mTabOptions.setTabListener(this);
		mActionBar.addTab(mTabFile, 0);
		mActionBar.addTab(mTabPeers, 1, false);
		mActionBar.addTab(mTabOptions, 2, false);

	}

	private void initTorrent() {
		mManager = ((FreeRemoteApplication) getSherlockActivity().getApplication()).getTransmissionManager();
		putObservable(mManager);
	}

	private void refreshListDataSet() {
		if (mTorrentStatus != null && mFileAdapter != null) {
			mFileAdapter.setTorrentFiles(mTorrentStatus.getFiles());
			mPeerAdapter.setTorrentFiles(mTorrentStatus.getPeers());
		}
	}

	private void makeRequest() {
		System.out.println("makeRequest");
		getSherlockActivity().setProgressBarIndeterminate(true);
		mManager.getTorrentDetails(requestedFields, mTorrentStatus.getId());
	}

	@Override
	public void update(Observable observable, Object data) {

		if (observable instanceof TransmissionManager) {
			getSherlockActivity().setProgressBarIndeterminate(false);
			TransmissionResult result = (TransmissionResult) data;
			if (result.mAction == ActionType.GetTorrentDetails) {
				if (data instanceof ArrayList) {

					if (((ArrayList<?>) data).size() > 0) {
						mTorrentStatus = (TorrentStatus) ((ArrayList<?>) data).get(0);
						refreshListDataSet();
					}
				}

				mTimer.setLastRefreshTime(System.currentTimeMillis());
				mTimer.reset();
			}
		}
	}

	@Override
	public void onTick() {
		makeRequest();

	}

	private class ViewHolderFile {
		TextView mFilename;
		TextView mSize;
		TextView mCompleted;
	}

	private class ViewHolderPeer {
		TextView mAddress;
		TextView mUpload;
		TextView mDownload;
	}

	private class TorrentFileAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		private ArrayList<TorrentFile> mFiles;

		public TorrentFileAdapter(Context context) {
			mFiles = new ArrayList<TorrentFile>();
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void setTorrentFiles(ArrayList<TorrentFile> files) {
			if (files != null) {
				mFiles = files;
				notifyDataSetChanged();
			}
		}

		@Override
		public int getCount() {
			return mFiles.size();
		}

		@Override
		public TorrentFile getItem(int position) {

			return mFiles.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolderFile holder;
			if (convertView == null) {
				holder = new ViewHolderFile();
				convertView = mInflater.inflate(R.layout.listitem_torrent_file, null);
				holder.mFilename = (TextView) convertView.findViewById(R.id.listitem_torrent_filename);
				holder.mSize = (TextView) convertView.findViewById(R.id.listitem_torrent_size);
				holder.mCompleted = (TextView) convertView.findViewById(R.id.listitem_torrent_completed);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolderFile) convertView.getTag();
			}
			TorrentFile file = getItem(position);
			Uri uri = Uri.parse("file:///".concat(file.getName()));
			holder.mFilename.setText(uri.getLastPathSegment());
			holder.mSize.setText(TorrentStatus.humanReadableSize(file.getSize()));
			holder.mCompleted.setText(TorrentStatus.humanReadableSize(file.getCompleted()));
			return convertView;
		}

	}

	private class PeerFileAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		private ArrayList<TorrentPeer> mPeers;

		public PeerFileAdapter(Context context) {
			mPeers = new ArrayList<TorrentPeer>();
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void setTorrentFiles(ArrayList<TorrentPeer> peers) {
			if (peers != null) {
				mPeers = peers;
				notifyDataSetChanged();
			}
		}

		@Override
		public int getCount() {
			return mPeers.size();
		}

		@Override
		public TorrentPeer getItem(int position) {
			return mPeers.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolderPeer holder;
			if (convertView == null) {
				holder = new ViewHolderPeer();
				convertView = mInflater.inflate(R.layout.listitem_torrent_peers, null);
				holder.mAddress = (TextView) convertView.findViewById(R.id.listitem_peer_address);
				holder.mUpload = (TextView) convertView.findViewById(R.id.listitem_peer_upload);
				holder.mDownload = (TextView) convertView.findViewById(R.id.listitem_peer_download);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolderPeer) convertView.getTag();
			}

			holder.mAddress.setText(getItem(position).getAddress());
			holder.mUpload.setText(String.valueOf(getItem(position).getRateToPeer()));
			holder.mDownload.setText(String.valueOf(getItem(position).getRateToClient()));
			return convertView;
		}
	}

	class WizardPagerAdapter extends PagerAdapter {

		public Object instantiateItem(View collection, int position) {

			int resId = 0;
			switch (position) {
			case 0:
				resId = R.id.fr_torrent_details_file;
				break;
			case 1:
				resId = R.id.fr_torrent_details_peer;
				break;
			case 2:
				resId = R.id.fr_torrent_details_infos;
				break;
			}
			return mView.findViewById(resId);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == ((View) arg1);
		}
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		mViewPager.setCurrentItem(tab.getPosition());

	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {

	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int position) {
		mActionBar.setSelectedNavigationItem(position);
	}

}
